package com.example.administrator.myapplication.service;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import android.text.TextUtils;
import android.util.Log;

import com.example.administrator.myapplication.model.User;

/**
 * Created by Administrator on 2017/8/5 0005.
 */

public final class DBManager {
    private WeChatDatabaseHelper dbh;
    private SQLiteDatabase sdb;
    private final static String TAG = "DBManager";
    public DBManager(Context context){
        dbh = new WeChatDatabaseHelper(context);
        sdb = dbh.getWritableDatabase();
        Log.i(TAG, "DBManager: 数据库存储位置："+sdb.getPath());
        
    }

    /**
     * 插入一条新的账户数据
     * @param user
     * @return
     */
    public boolean add(final User user){
        if(query(user.getUsername())!=null) {
            return false;
        }else if (empty(user)) {
            return false;
        }

        sdb.beginTransaction();
        try {
            sdb.execSQL("INSERT INTO user_table(username,password) VALUES ( ?, ?)", new Object[]{user.getUsername(), user.getPassword()});
            sdb.setTransactionSuccessful();
        }finally {
            sdb.endTransaction();
        }
        return true;
    }

    /**
     * 将账户的状态持久化至数据库
     * @param landingStatus true 如果登录成功
     * @param user
     * @return true 如果更新成功
     */
    public boolean updateLandingStatus(boolean landingStatus, User user){
        if(empty(user)){
            return false;
        }
        sdb.beginTransaction();
        try {
            sdb.execSQL("UPDATE user_table SET landing_status = ? WHERE username = ? AND password = ?",new Object[]{landingStatus, user.getUsername(),user.getPassword()});
            sdb.setTransactionSuccessful();
        }finally {
            sdb.endTransaction();
        }
        return true;

    }


    public User queryAccountLandingStatus(final User user){
        if(empty(user)){
            return null;
        }
      User user1 = null;
      Cursor c = sdb.rawQuery("SELECT * FROM user_table WHERRE username = ? AND password = ?",new String[]{user.getUsername(), user.getPassword()});
      if(c.moveToFirst()){
          user1 = user;
          user1.setLanding_status(Boolean.getBoolean(c.getString(c.getColumnIndex("landing_status"))));
          return user1;
      }
      return null;
    }

    /**
     * 从数据库中查询处于登录状态的账户
     * @param landingStatus
     * @return
     */
    @Deprecated
    public User queryAccountLandingStatusIsLogIn(final boolean landingStatus){

        String landingStatus_s = String.valueOf(landingStatus ? 1 : 0);
       Cursor c =  sdb.rawQuery("SELECT * FROM user_table WHERE landing_status = ?",new String[]{landingStatus_s});
        User user = null;
        if(c.moveToFirst()){
            user = new User();
            Log.i(TAG, "queryAccountLandingStatusIsLogIn: 处于离线登录状态的账户为："+Boolean.getBoolean(c.getString(c.getColumnIndex("landing_status"))));
            user.setLanding_status(Boolean.getBoolean(c.getString(c.getColumnIndex("landing_status"))));
            user.setUsername(c.getString(c.getColumnIndex("username")));
            user.setPassword(c.getString(c.getColumnIndex("password")));
            return user;
        }
        return null;
    }

    /**
     * 查询用户名在数据表中是否已经存在
     * @param username
     * @return User 如果存在,否则 NUll
     */
    public User query( final String username){
        if(TextUtils.isEmpty(username)){
            throw new NullPointerException("用户名不允许为空值");
        }
        User user=null;
        Cursor c = sdb.rawQuery("SELECT username,password,landing_status FROM user_table WHERE username = ?",new String[]{username});
        if (c.moveToFirst()){
            user = new User();
            Log.i(TAG, "queryAccountLandingStatusIsLogIn: 处于离线登录状态的账户为："+Boolean.getBoolean(c.getString(c.getColumnIndex("landing_status"))));
            user.setLanding_status(Boolean.getBoolean(c.getString(c.getColumnIndex("landing_status"))));
            user.setUsername(c.getString(c.getColumnIndex("username")));
            user.setPassword(c.getString(c.getColumnIndex("password")));
            return user;
        }
        return null;

    }

    /**
     *
     * @param user
     * @return true, 如果对象正确
     */
    public boolean query( final User user){
        if(empty(user))
            return false;

        Cursor c = sdb.rawQuery("SELECT * FROM user_table WHERE username = ? AND password = ?",new String[]{user.getUsername(), user.getPassword()});
        if(c.getCount() >= 1){
            return true;
        }else {
            return false;
        }

    }

    /**
     *
     * @param user
     * @return true 如果用户名或密码其中一个为空
     */
    private boolean empty(User user){
        if (TextUtils.isEmpty(user.getUsername()) | TextUtils.isEmpty(user.getPassword()) ){
            return true;
        }
        return false;
    }

}
